﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Syndication;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Xml;

namespace Scrummer.Feed
{
	// NOTE: If you change the class name "DefaultScrummerFeed" here, you must also update the reference to "DefaultScrummerFeed" in App.config.
	public class DefaultScrummerFeed : IScrummerFeed
	{
		private readonly IList<string> urls = new List<string>();

		public DefaultScrummerFeed()
		{
			urls.Add("http://feeds.feedburner.com/improvingblogs");
		}

		public SyndicationFeedFormatter ViewFeed()
		{
				// Create a new Syndication Feed.
			SyndicationFeed feed = new SyndicationFeed("Scrummer Feed", "A scrummer.org custom feed", null)
				       	{Items = new List<SyndicationItem>()};

			WebClient client = new WebClient();
			List<SyndicationItem> items = new List<SyndicationItem>();

			foreach (string url in urls)
			{
				SyndicationFeed singleFeed = DownloadFeed(url, client);
				items.AddRange(singleFeed.Items);
			}

			feed.Items = items;
			feed.Items.OrderBy(item => item.PublishDate);

			return ResolveFormatter(feed);
		}


		public bool AddFeed(string encodedUrl)
		{
			try
			{
				string feedUrl = HttpUtility.UrlDecode(encodedUrl);

				SyndicationFeed feed = DownloadFeed(feedUrl, new WebClient());

				if(feed != null && feed.Items != null)
				{
					urls.Add(feedUrl);
					return true;
				}
				else
				{
					return false;
				}
			}
			catch (Exception)
			{
				return false;
			}
		}

		private SyndicationFeed DownloadFeed(string url, WebClient request)
		{
			string xml = request.DownloadString(url);
			XmlReader reader = XmlReader.Create(new StringReader(xml));
			SyndicationFeed feed = SyndicationFeed.Load(reader);

			return feed;
		}

		private SyndicationFeedFormatter ResolveFormatter(SyndicationFeed feed)
		{
			// Return ATOM or RSS based on query string
			// rss -> http://localhost:8731/Design_Time_Addresses/Scrummer.Feed/DefaultScrummerFeed/
			// atom -> http://localhost:8731/Design_Time_Addresses/Scrummer.Feed/DefaultScrummerFeed/?format=atom
			string query = null;
			if (WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.UriTemplateMatch != null)
			{
				query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
			}

			SyndicationFeedFormatter formatter = null;
			if (query == "atom")
			{
				formatter = new Atom10FeedFormatter(feed);
			}
			else
			{
				formatter = new Rss20FeedFormatter(feed);
			}

			return formatter;
		}
	}
}
